/*
 * @Description: 检测模板配置弹窗
 * @Author: Zzt
 * @Date: 2022-10-10 17:35:18
 * @LastEditTime: 2023-02-10 20:18:14
 */

import { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input, message, Modal, Select, Space, Tabs } from 'antd';
import classNames from 'classnames/bind';
import { fetchDetectionList } from '@/api/standardizedDetection/detectionPlan';
import { selectItemByKey } from '@/utils/list';
import { CheckCircleFilled } from '@ant-design/icons';
import type { Key } from 'react';
import styles from '../../styles/index.module.scss';
import { useDetectionTemplateContext } from '../../contexts/DetectionTemplateContext';
import JPModal from '@/components/JPComponents/JPModal';

const cx = classNames.bind(styles);
const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const inspection = [
  { id: 1, name: '条目检测', sortNo: 5 },
  { id: 2, name: '原文检测', sortNo: 4 },
  { id: 3, name: 'EEP格式包检测', sortNo: 3 },
  { id: 4, name: '光盘格式包检测', sortNo: 2 },
  { id: 5, name: '系统环境检测', sortNo: 1 }
];

const type = [
  { id: 1, value: '条目与原文' },
  { id: 2, value: '条目' },
  { id: 3, value: '原文' },
  { id: 4, value: 'EEP格式包' },
  { id: 5, value: '光盘格式' },
  { id: 6, value: '系统环境' }
];

/**
 * @description:根据id插入条件
 * @param {number} id 更新项目id
 * @param {Object} data 插入的数据
 * @param {Array<Object>} list 原表格数据列表
 * @param {string} key 对应字段
 * @return {Array<Object>} 处理后的表格数据列表
 */
function updateById(id: any, data: any, list: any, key = 'sortNo') {
  if (list.length === 0) {
    list.push(data);
  } else {
    const finds = list.find((item: any) => item.sortNo === id);
    if (finds === undefined) {
      list.push(data);
    } else {
      for (let i = 0; i < list.length; i++) {
        if (list[i][key] === id) list.splice(i, 1, { ...list[i], ...data });
      }
    }
  }
  return list.map((item: any) => item);
}

const TemplateConfiguration = (props: any) => {
  const [form] = Form.useForm();
  const { visible, onClose, fileData, ArchiveAndDetection, archiveTypeList } = props;
  const { addTemplateTaskList, deleteTemplateFunc, editTemplateTask } =
    useDetectionTemplateContext();
  const [atConditionList, setAtConditionList] = useState([]);
  // 方案类型选择
  const [programme, setProgramme] = useState<number>(0);
  // 检测内容选择
  const [selectPRId, setSelectPRId] = useState<Key[]>([]);
  // 档案类型id
  const [archiveTypeId, setArchiveTypeId] = useState<number>();
  // 检测方案查询结果
  const [plainOptions, setPlainOptions] = useState([]);

  /**
   * @description: 切换方案类型
   * @param {number} val 选中的方案的类型
   */
  const handleTypeChange = (val: any) => {
    setProgramme(parseInt(val, 10));
  };

  useEffect(() => {
    form.resetFields();
    form.setFieldsValue(ArchiveAndDetection);
    console.log(fileData);
    if (visible) {
      fetchDetectionList({ archiveTypeId: ArchiveAndDetection.archiveTypeId }).then((res) => {
        const { data } = res;
        setPlainOptions(data);
      });
      if (fileData.id) {
        if (fileData.schemeIdList) {
          setAtConditionList(fileData.schemeIdList);
        }
        form.setFieldsValue({
          ...fileData
        });
        setProgramme(inspection[0].id);
      } else {
        setProgramme(inspection[0].id);
      }
    } else {
      setArchiveTypeId(null);
      setProgramme(0);
      setAtConditionList([]);
      setSelectPRId([]);
      form.resetFields();
    }
  }, [visible]);

  // 切换方案类型自动加载方案列表
  useEffect(() => {
    // setPlainOption(plainOptions.filter((item) => item.detectionObjType === programme));
    if (atConditionList && atConditionList.length > 0) {
      setSelectPRId([
        atConditionList.find(
          (item: any) => item.sortNo === inspection.find((item) => item.id === programme).sortNo
        )?.schemeId
      ]);
    }
  }, [programme]);

  useEffect(() => {
    // onChange({ atConditionList });

    if (programme) {
      console.log(atConditionList);
      const condition = {
        schemeId: selectPRId[0],
        sortNo: inspection.find((item) => item.id === programme).sortNo
      };
      setAtConditionList(
        updateById(
          inspection.find((item) => item.id === programme).sortNo,
          condition,
          atConditionList
        )
      );
    }
  }, [selectPRId]);
  // 点击方案列表
  const onChange = (checkedValues: any) => {
    setSelectPRId((state) =>
      state.length === 0 || checkedValues.length === 0
        ? checkedValues
        : [checkedValues.find((item: any) => item !== state[0])]
    );
    // const condition = { id: programme, select: selectPRId };
  };

  /**
   * @description 提交表单，触发onFinish方法
   */
  const submitFunc = () => {
    form.submit();
  };
  /* 根据 */
  const onFinish = (values: any) => {
    if (atConditionList.some((item) => item.schemeId)) {
      const param = {
        ...ArchiveAndDetection,
        schemeIdList: atConditionList,
        templateName: values.templateName,
        templateDesc: values.templateDesc
      };
      if (fileData.id) {
        editTemplateTask({
          schemeIdList: fileData.schemeIdList,
          templateName: fileData.templateName,
          ...param,
          id: fileData.id
        });
      } else {
        addTemplateTaskList({ ...param });
      }
      form.setFieldsValue({});
      onClose();
    } else {
      message.error('请至少选择一个方案类型');
    }
  };

  const showFondCheck = (id: number) => {
    const fondObj = selectItemByKey(id, atConditionList, 'sortNo');
    return !!(fondObj && fondObj?.schemeId);
  };

  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };
  return (
    <JPModal
      // draggable={true}
      visible={visible}
      title={'规范性检测任务'}
      width={700}
      onCancel={onClose}
      footer={[
        <div key="delBackSubmit">
          {fileData.id ? (
            <Button
              style={{ float: 'left' }}
              onClick={() => {
                deleteTemplateFunc([fileData.id], '是否移除此模板？移除后不可恢复');
                onClose();
              }}
            >
              删除
            </Button>
          ) : (
            ''
          )}
          <Button key="back" onClick={onClose}>
            取消
          </Button>
          <Button key="submit" type="primary" onClick={() => submitFunc()}>
            保存
          </Button>
        </div>
      ]}
    >
      <Form form={form} onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        <Form.Item name="templateName" label="检测模板名称" rules={[{ required: true }]}>
          <Input placeholder="请设置检测模板名称"></Input>
        </Form.Item>
        <Form.Item label="档案类型" name="archiveTypeId">
          <Select onChange={handleChange} placeholder="=请选择档案类型=" disabled>
            {archiveTypeList.map((item: any) => (
              <Option value={item.id} key={item.id}>
                {item.atName}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="检测类型" name="detectionType">
          <Select onChange={handleChange} placeholder="=请选择检测类型=" disabled>
            {type.map((item) => (
              <Option value={item.id} key={item.id}>
                {item.value}检测
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="templateDesc" label="检测模板说明">
          <TextArea rows={4} placeholder="检测模板说明" />
        </Form.Item>
      </Form>
      <div>
        <div className={cx('tem-explain')}>
          <Tabs
            activeKey={programme + ''}
            tabBarGutter={4}
            size={'small'}
            tabPosition="left"
            className={cx('tab')}
            onTabClick={handleTypeChange}
            tabBarExtraContent={{
              left: (
                <Button type="text" disabled>
                  方案类型
                </Button>
              )
            }}
            // style={{ height: 220 }}
          >
            {/* 遍历获取 */}
            {/* <Button disabled> 方案类型</Button> */}
            {inspection.map((item) => (
              <TabPane
                tab={
                  <>
                    {showFondCheck(item.sortNo) && (
                      <CheckCircleFilled className={cx('fond-checked')} />
                    )}
                    {item.name}
                  </>
                }
                key={item.id}
              >
                <Checkbox.Group onChange={onChange} value={selectPRId}>
                  <Space direction="vertical">
                    {plainOptions
                      .filter((item) => item.detectionObjType === programme)
                      .map((item) => (
                        <Checkbox value={item.id} key={item.id}>
                          {item.schemeName}
                        </Checkbox>
                      ))}
                  </Space>
                </Checkbox.Group>
              </TabPane>
            ))}
          </Tabs>
        </div>
        <div className={cx('tem-explain')}>
          <p>
            <b>方案类型说明：</b>以上检测方案类型可灵活组合，生成检测模板。
          </p>
          <p>条目检测:对档案元数据进行规范性检测</p>
          <p>原文检测：对原文进行规范性检测</p>
          <p>EEP格式包检测:对EEP格式包组织、规范进行检测</p>
          <p>光盘格式包：对光盘格式包组织、规范进行检测</p>
          <p>系统环境检测：对档案业务处理时的系统安全性进行检测</p>
        </div>
      </div>
    </JPModal>
  );
};
export default TemplateConfiguration;
